package com.nx.platform.es.bean.modle.sort;

import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.sort.ScriptSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class PainlessScriptSortHandler implements SortFieldHandler {

    @Override
    public SortBuilder<?> handle(ImmutableMap<String, ?> fieldConfig, Map<String, Object> params, SortOrder sortOrder) {
        String inline = MapUtils.getString(fieldConfig, "inline");
        Script script = new Script(ScriptType.INLINE, "painless", inline, params);
        ScriptSortBuilder builder = SortBuilders.scriptSort(script, ScriptSortBuilder.ScriptSortType.NUMBER);
        if (sortOrder != null) {
            return builder.order(sortOrder);
        }
        Object order = MapUtils.getObject(fieldConfig, "order");
        if (order instanceof SortOrder) {
            return builder.order((SortOrder) order);
        }
        return builder.order(SortOrder.DESC);
    }

}
